<template>
  <div class="addShop">
    <headTop></headTop>
    <el-row style="margin-top: 40px">
      <el-col :span="12" :offset="4">
        <el-form
          ref="formData"
          :model="formData"
          :rules="rules"
          label-width="80px"
        >
          <el-form-item label="店铺名称" prop="name">
            <el-input v-model="formData.name"></el-input>
          </el-form-item>
          <el-form-item label="详情地址" prop="address">
            <el-autocomplete
              class="inline-input"
              style="width: 100%"
              v-model="formData.address"
              :fetch-suggestions="querySearch"
              :trigger-on-focus="false"
              placeholder="请输入地址"
              @select="handleSelect"
            ></el-autocomplete>
            <span>当前城市:{{ city.name }}</span>
          </el-form-item>
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="formData.phone"></el-input>
          </el-form-item>
          <el-form-item label="店铺简介">
            <el-input v-model="formData.description"></el-input>
          </el-form-item>
          <el-form-item label="店铺标语">
            <el-input v-model="formData.promotion_info"></el-input>
          </el-form-item>
          <el-form-item label="店铺分类">
            <el-cascader
              v-model="selectedCategory"
              :options="categoryOptions"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="店铺特点">
            <span>品牌保证</span>
            <el-switch v-model="formData.is_premium"></el-switch>
            <span>蜂鸟专送</span>
            <el-switch v-model="formData.delivery_mode"></el-switch>
            <span>新开店铺</span>
            <el-switch v-model="formData.new"></el-switch>
          </el-form-item>
          <el-form-item label="">
            <span>外卖保</span>
            <el-switch v-model="formData.bao"></el-switch>
            <span>准时保</span>
            <el-switch v-model="formData.zhun"></el-switch>
            <span>开发票</span>
            <el-switch v-model="formData.piao"></el-switch>
          </el-form-item>
          <el-form-item label="配送费">
            <el-input-number
              v-model="formData.float_delivery_fee"
              :min="0"
              :max="20"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="起送价">
            <el-input-number
              v-model="formData.float_minimum_order_amount"
              :min="0"
              :max="100"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="营业时间">
            <el-time-select
              v-model="formData.startTiem"
              :picker-options="{
                start: '05:30',
                step: '00:15',
                end: '23:30',
              }"
              placeholder="营业时间"
            >
            </el-time-select>
            <el-time-select
              v-model="formData.endTiem"
              :picker-options="{
                start: '05:30',
                step: '00:15',
                end: '23:30',
              }"
              placeholder="停业时间"
            >
            </el-time-select>
          </el-form-item>
          <el-form-item label="上传店铺头像">
            <el-upload
              class="avatar-uploader"
              :action="baseUrl + '/v1/addimg/shop'"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img
                v-if="formData.image_path"
                :src="baseImgPath + formData.image_path"
                class="avatar"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="上传营业执照">
            <el-upload
              class="avatar-uploader"
              :action="baseUrl + '/v1/addimg/shop'"
              :show-file-list="false"
              :on-success="handleBusinessAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img
                v-if="formData.business_license_image"
                :src="baseImgPath + formData.business_license_image"
                class="avatar"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="上传服务许可证">
            <el-upload
              class="avatar-uploader"
              :action="baseUrl + '/v1/addimg/shop'"
              :show-file-list="false"
              :on-success="handleCateringAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img
                v-if="formData.catering_service_license_image"
                :src="baseImgPath + formData.catering_service_license_image"
                class="avatar"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="优惠活动">
            <el-select
              v-model="activityValue"
              @change="selectActiviry"
              placeholder="请选择"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-table
            :cell-style="{ textAlign: 'center' }"
            :header-cell-style="{
              color: 'black',
              background: '#eef1f6',
              textAlign: 'center',
            }"
            :data="activities"
            style="min-width: 600px; margin-bottom: 20px"
          >
            <el-table-column prop="icon_name" label="活动标题" width="120">
            </el-table-column>
            <el-table-column prop="name" label="活动名称" width="120">
            </el-table-column>
            <el-table-column prop="description" label="活动详情">
            </el-table-column>
            <el-table-column label="操作" width="120">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="danger"
                  @click="delActivities(scope)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <el-form-item>
            <el-button type="primary" @click="onSubmit('formData')"
              >立即创建</el-button
            >
            <el-button>取消</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import headTop from "../components/headTop";
import { cityGuess, foodCategory, searchplace, addShop } from "../api/getData";
import { baseUrl, baseImgPath } from "../config/env";
export default {
  data() {
    return {
      baseUrl,
      baseImgPath,
      // 当前城市
      city: {},
      formData: {
        name: "",
        address: "", // 地址
        phone: null,
        latitude: "", // 维度
        longitude: "", // 经度
        description: "", // 介绍
        promotion_info: "", // 标语
        is_premium: true,
        delivery_mode: true,
        new: true, // 新开店铺
        bao: true, //支持保险
        zhun: true, // 准时达
        piao: true, // 开发票
        startTiem: "", // 营业时间
        endTiem: "", // 停业时间
        float_delivery_fee: 0, // 运费
        float_minimum_order_amount: 0, // 起送价
        image_path: "", // 商铺图片地址
        business_license_image: "", // 营业执照图片地址
        catering_service_license_image: "", // 服务许可证图片地址
      },
      selectedCategory: ["快餐便当", "简餐"],
      categoryOptions: [],
      // 校验规则
      rules: {
        name: [{ required: true, message: "请输入店铺名称", trigger: "blur" }],
        address: [
          { required: true, message: "请输入详细地址", trigger: "blur" },
        ],
        phone: [
          { required: true, message: "请输入联系电话" },
          { pattern: /^1[3456789]\d{9}$/, message: "电话号码必须是数字" },
        ],
      },
      //优惠活动
      options: [
        {
          value: "满减优惠",
          label: "满减优惠",
        },
        {
          value: "优惠大酬宾",
          label: "优惠大酬宾",
        },
        {
          value: "进店领卷",
          label: "进店领卷",
        },
      ],
      activityValue: "满减优惠",
      activities: [
        {
          icon_name: "减",
          name: "满减优惠",
          description: "满30减5，满60减8",
        },
      ],
    };
  },
  // 组件
  components: {
    headTop,
  },
  created() {
    this.initData();
  },
  methods: {
    async initData() {
      // 获取当前城市
      const { data } = await cityGuess();
      this.city = data;
      // 获取食物种类
      const { data: category } = await foodCategory();
      console.log(category);
      category.forEach((item) => {
        if (item.sub_categories.length) {
          const addnew = {
            value: item.name,
            label: item.name,
            children: [],
          };
          item.sub_categories.forEach((subitem, index) => {
            if (index == 0) {
              return;
            }
            addnew.children.push({
              value: subitem.name,
              label: subitem.name,
            });
          });
          this.categoryOptions.push(addnew);
        }
      });
      console.log("食物种类==", category);
    },
    // 上传图片
    // 上传商铺图片
    handleAvatarSuccess(res, file) {
      if (res.status) {
        this.formData.image_path = res.image_path;
      } else {
        this.$message.error("上传图片失败!");
      }
    },
    // 上传营业执照
    handleBusinessAvatarSuccess(res, file) {
      if (res.status) {
        this.formData.business_license_image = res.image_path;
      } else {
        this.$message.error("上传图片失败！");
      }
    },
    // 上传服务许可证
    handleCateringAvatarSuccess(res, file) {
      if (res.status) {
        this.formData.catering_service_license_image = res.image_path;
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 优惠活动事件
    selectActiviry() {
      console.log("优惠活动");
      this.$prompt("请输入活动详情", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputValidator: (data) => {
          if (data == null) return "请输入活动详情";
        },
      })
        .then(({ value }) => {
          console.log("确定====", value);
          let newObj = {};
          switch (this.activityValue) {
            case "满减优惠":
              newObj = {
                icon_name: "减",
                name: "满减优惠",
                description: value,
              };
              break;
            case "优惠大酬宾":
              newObj = {
                icon_name: "特",
                name: "优惠大酬宾",
                description: value,
              };
              break;
            case "新用户立减":
              newObj = {
                icon_name: "新",
                name: "新用户立减",
                description: value,
              };
              break;
            case "进店领卷":
              newObj = {
                icon_name: "领",
                name: "进店领卷",
                description: value,
              };
              break;
          }
          this.activities.push(newObj);
        })
        .catch((err) => {
          this.$message({
            type: "info",
            message: "取消输入",
          });
        });
    },
    // 删除优惠活动
    delActivities(scope) {
      this.activities.splice(scope.$index, 1);
    },

    // 获取搜索地址
    async querySearch(queryString, cb) {
      console.log("queryString===", queryString);
      // console.log("cb===", cb);

      if (queryString) {
        try {
          const { data } = await searchplace(this.city.id, queryString);
          console.log("搜索地址===", data);
          if (data instanceof Array) {
            data.map((item) => {
              item.value = item.address;
              return item;
            });
            console.log(data);
            cb(data);
          }
        } catch (err) {
          console.log(err);
        }
      }
    },
    handleSelect(item) {
      console.log("888888", item);
      this.formData.latitude = item.latitude;
      this.formData.longitude = item.longitude;
    },
    //  添加商铺
    async onSubmit(formData) {
      console.log("submit!", formData);
      try {
        await this.$refs[formData].validate();
        Object.assign(
          this.formData,
          { activities: this.activities },
          { category: this.selectedCategory.join("/") }
        );
        const res = await addShop(this.formData);
        console.log("添加商铺===", res);
        if (res.status == 1) {
          this.$message({
            type: "success",
            message: "添加成功",
          });
          this.formData = {
            name: "",
            address: "", // 地址
            phone: null,
            latitude: "", // 维度
            longitude: "", // 经度
            description: "", // 介绍
            promotion_info: "", // 标语
            is_premium: true,
            delivery_mode: true,
            new: true, // 新开店铺
            bao: true, //支持保险
            zhun: true, // 准时达
            piao: true, // 开发票
            startTiem: "", // 营业时间
            endTiem: "", // 停业时间
            float_delivery_fee: 0, // 运费
            float_minimum_order_amount: 0, // 起送价
            image_path: "", // 商铺图片地址
            business_license_image: "", // 营业执照图片地址
            catering_service_license_image: "", // 服务许可证图片地址
          };
        } else {
          this.$message({
            type: "error",
            message: res.message,
          });
        }
      } catch (err) {
        console.log(err);
      }
    },
  },
};
</script>

<style lang="less" >
@import "../style/mixin.less";
.addShop {
  .el-switch {
    margin: 0 6px;
  }
  .el-date-editor.el-input {
    margin-right: 5px;
  }
  // 上传图片
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
  }
  .avatar {
    width: 120px;
    height: 120px;
    display: block;
  }
}
// 表格
.el-table {
  border: 1px solid #b6bec5;
  td,
  th {
    padding: 6px 0;
  }
}
</style>